package net.hserver.gateway.task;

import lombok.extern.slf4j.Slf4j;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.ioc.annotation.Task;
import net.hserver.gateway.core.statistics.StatisticsData;
import net.hserver.gateway.dao.GatewayStatisticsDao;
import net.hserver.gateway.entity.GateWayStatistics;
import net.hserver.gateway.utils.UUIDUtil;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author hxm
 */
@Bean
@Slf4j
public class StatisticsTask {

    @Autowired
    private GatewayStatisticsDao statisticsDao;

    /**
     * 应该每天24小时存一次，当天的直接看热点数据
     */
    @Task(name = "StatisticsTask", time = "10000")
    public void checkTask() {
        log.info("统计数据存储");
        //结果
        StatisticsData.Data data = StatisticsData.clearAndGet();
        LocalDate now = LocalDate.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = now.format(fmt);
        List<GateWayStatistics> select = statisticsDao.createLambdaQuery().andEq(GateWayStatistics::getCreateTime, dateStr).select();
        if (select.size()==0){
            //插入新的，
            GateWayStatistics build =new  GateWayStatistics();
            build.setId(UUIDUtil.randomUUID32());
            build.setUv(data.getUv().toString());
            build.setPv(data.getPv().toString());
            build.setAndroidPlatform(data.getAndroidPlatform().toString());
            build.setIosPlatform(data.getIosPlatform().toString());
            build.setPcPlatform(data.getPcPlatform().toString());
            build.setOtherPlatform(data.getOtherPlatform().toString());
            build.setCreateTime(dateStr);
            statisticsDao.insert(build);
            return;
        }
        GateWayStatistics gateWayStatistics = select.get(0);
        //叠加更新。
        gateWayStatistics.setUv(String.valueOf((data.getUv()+Long.parseLong(gateWayStatistics.getUv()))));
        gateWayStatistics.setPv(String.valueOf((data.getPv()+Long.parseLong(gateWayStatistics.getPv()))));
        gateWayStatistics.setAndroidPlatform(String.valueOf((data.getAndroidPlatform()+Long.parseLong(gateWayStatistics.getAndroidPlatform()))));
        gateWayStatistics.setIosPlatform(String.valueOf((data.getIosPlatform()+Long.parseLong(gateWayStatistics.getIosPlatform()))));
        gateWayStatistics.setPcPlatform(String.valueOf((data.getPcPlatform()+Long.parseLong(gateWayStatistics.getPcPlatform()))));
        gateWayStatistics.setOtherPlatform(String.valueOf((data.getOtherPlatform()+Long.parseLong(gateWayStatistics.getOtherPlatform()))));
        statisticsDao.updateById(gateWayStatistics);
    }

}
